import {
	Button,
	Form,
	Row,
	Col,
	Input,
	Select,
	Upload,
	message,
	TreeSelect,
} from 'antd'
import React, {useState, useEffect} from 'react'
import {connect, history, useModel} from 'umi'
import type {UploadFile} from 'antd/es/upload/interface'
import styles from './index.less'
import VehicleTable from '../../components/VehicleTable'
import {uploadFileUrl} from '@/service/common/upload'
import {addAllocationno} from '@/service/storage/allocation'
import Modal from '@/components/Modal'
import {getCommonCompanyCity, getCompany} from '@/service/common'
import {translateDataToTree} from '@/utils/common'
import {getCompanyScope} from '@/service/system/company'

const {TextArea} = Input

const fieldNames = {
	label: 'name',
	value: 'id',
	id: 'id',
	pId: 'parentId',
}

const add = (props: any) => {
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const [basicsForm] = Form.useForm()
	const [enclosureForm] = Form.useForm()
	const [isModalOpen, setIsModalOpen] = useState(false)
	// 选择的列表数据
	const [dataList, setDataList] = useState<any>([])
	const [formData, setFormData] = useState<any>({})
	const [fileList, setFileList] = useState<UploadFile[]>([])
	const [companyData, setCompanyData] = useState([])
	const [inCompanyData, setInCompanyData] = useState([])
	// 调出公司Id
	const [moveOutCompanyId, setMoveOutCompanyId] = useState()
	const [moveInCompanyId, setMoveInCompanyId] = useState()
	const [moveOutCompanyCitysList, setMoveOutCompanyCitysList] = useState<
		any[]
	>([])
	const [moveInCompanyCitysList, setMoveInCompanyCitysList] = useState<any[]>(
		[],
	)
	const [moveOutCityId, setMoveOutCityId] = useState<string>('')
	const [moveOutCityName, setMoveOutCityName] = useState<string>('')
	const [moveInCityName, setMoveInCityName] = useState<string>('')
	const [btnLoading, setBtnLoading] = useState(false)

	/** 获取公司的城市 */
	const onCompanyCity = (
		value: string | number,
		moveType: string,
		cityName?: string,
		replace?: string,
	) => {
		getCommonCompanyCity({merchantId: value})
			.then((res: any) => {
				if (res?.success) {
					if (moveType === 'moveOut') {
						const cityData = res?.data.map((item: any) => {
							const newData = {...item}
							if (item?.cityName === cityName) {
								newData.disabled = true
							}
							return newData
						})
						setMoveOutCompanyCitysList(cityData)
						if (!replace) {
							basicsForm.setFieldsValue({cityId: undefined})
						}
					} else {
						const cityData = res?.data.map((item: any) => {
							const newData = {...item}
							if (item?.cityName === cityName) {
								newData.disabled = true
							}
							return newData
						})
						setMoveInCompanyCitysList(cityData)
						if (!replace) {
							basicsForm.setFieldsValue({
								moveInCity: undefined,
							})
						}
					}
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}

	/** 获取调出公司数据 */
	const onCompany = () => {
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			const list = translateDataToTree(res.data)
			setCompanyData(list as any)
		})
	}
	/** 获取调入公司数据 */
	const onInCompany = () => {
		getCompanyScope().then((res: any) => {
			const list = translateDataToTree(res.data)
			setInCompanyData(list as any)
		})
	}
	useEffect(() => {
		onCompany()
		setMoveOutCompanyId(props?.user?.orgId)
		onCompanyCity(props?.user?.orgId, 'moveOut')
		basicsForm.setFieldsValue({orgId: props?.user?.orgId})
	}, [props?.user?.orgId])
	useEffect(() => {
		onInCompany()
	}, [])

	const onSave = async () => {
		const uploadFile = fileList?.map(
			(item) => item?.response?.data?.id || item?.uid,
		)
		const basicsValue = await basicsForm.validateFields()
		const enclosureValue = await enclosureForm.validateFields()
		if (basicsValue && enclosureValue) {
			if (dataList?.length) {
				setFormData({
					...basicsValue,
					...enclosureValue,
					uploadFile: uploadFile.toString(),
					carList: dataList,
					moveOutCityName,
					moveInCityName,
				})
				setIsModalOpen(true)
			} else {
				message.warning('请选择调拨车辆')
			}
		}
	}

	const onSubmit = () => {
		setBtnLoading(true)
		addAllocationno(formData)
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					history.goBack()
				}
				setBtnLoading(false)
			})
			.catch((err: any) => {
				message.error(err)
				setBtnLoading(false)
			})
	}
	const normFile = (e: any) => {
		if (Array.isArray(e)) {
			return e
		}
		return e?.fileList
	}
	const uploadProps = {
		action: uploadFileUrl,
		name: fileName,
		data: {
			modelName: 'storage_allocation',
			targetAttr: 1,
		},
		onChange(info: any) {
			if (info.file.status === 'done') {
				setFileList(info?.fileList)
			}
		},
		fileList,
	}

	return (
		<div className={styles.add}>
			<div className={styles.title}>调拨发起</div>
			<Form
				className={styles.basicsForm}
				form={basicsForm}
				name="basic"
				layout="horizontal"
				labelCol={{flex: '140px'}}
				labelAlign="right"
				labelWrap
				autoComplete="off">
				<Row gutter={12}>
					<Col sm={{span: 24}} md={{span: 12}}>
						<Form.Item
							label="调出公司名称"
							name="orgId"
							rules={[{required: true}]}>
							<TreeSelect
								showSearch
								style={{width: '100%'}}
								dropdownStyle={{
									maxHeight: 400,
									overflow: 'auto',
								}}
								placeholder="请选择"
								treeNodeFilterProp="name"
								treeDefaultExpandAll
								fieldNames={fieldNames}
								treeDataSimpleMode
								treeData={companyData}
								onChange={(value) => {
									setMoveOutCompanyId(value)
									setDataList([])
									onCompanyCity(
										value,
										'moveOut',
										moveInCityName,
									)
								}}
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}}>
						<Form.Item
							label="调入公司名称"
							name="moveInCompany"
							rules={[{required: true}]}>
							<TreeSelect
								showSearch
								treeNodeFilterProp="name"
								style={{width: '100%'}}
								dropdownStyle={{
									maxHeight: 400,
									overflow: 'auto',
								}}
								placeholder="请选择"
								treeDefaultExpandAll
								fieldNames={fieldNames}
								treeDataSimpleMode
								treeData={inCompanyData}
								onChange={(value) => {
									setMoveInCompanyId(value)
									onCompanyCity(
										value,
										'moveIn',
										moveOutCityName,
									)
								}}
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}}>
						<Form.Item
							label="调出城市"
							name="cityId"
							rules={[{required: true}]}>
							<Select
								placeholder="请选择"
								fieldNames={{
									value: 'cityId',
									label: 'cityName',
								}}
								onChange={(value, key) => {
									setMoveOutCityName(key?.cityName)
									setMoveOutCityId(value)
									setDataList([])
									if (moveInCompanyId) {
										onCompanyCity(
											moveInCompanyId,
											'moveIn',
											key?.cityName,
											'replace',
										)
									}
								}}
								options={moveOutCompanyCitysList}
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}}>
						<Form.Item
							label="调入城市"
							name="moveInCity"
							rules={[{required: true}]}>
							<Select
								placeholder="请选择"
								fieldNames={{
									value: 'cityId',
									label: 'cityName',
								}}
								onChange={(value, key) => {
									setMoveInCityName(key?.cityName)
									if (moveOutCompanyId) {
										onCompanyCity(
											moveOutCompanyId,
											'moveOut',
											key?.cityName,
											'replace',
										)
									}
								}}
								options={moveInCompanyCitysList}
							/>
						</Form.Item>
					</Col>
				</Row>
			</Form>
			<VehicleTable
				companyId={moveOutCompanyId}
				data={dataList}
				setDataList={setDataList}
				cityId={moveOutCityId}
			/>
			<div className={styles.title}>调拨发起资料上传</div>
			<Form
				form={enclosureForm}
				name="enclosure"
				layout="horizontal"
				labelCol={{flex: '140px'}}
				labelAlign="right"
				labelWrap
				autoComplete="off">
				<Row gutter={12}>
					<Col span={24}>
						<Form.Item
							name="uploadFile"
							label="调拨附件"
							valuePropName="fileList"
							getValueFromEvent={normFile}
							rules={[
								{required: true, message: '请上传调拨附件'},
							]}
							className={styles.fileUpload}>
							<Upload {...uploadProps}>
								{fileList.length >= 3 ? null : (
									<Button>请选择文件</Button>
								)}
							</Upload>
						</Form.Item>
						<div className={styles.uploadTip}>
							附件说明：附件最大支持20M，支持格式：PDF、Word、Excel、JPG、PNG
						</div>
					</Col>
					<Col span={18}>
						<Form.Item label="备注" name="remarks">
							<TextArea
								maxLength={200}
								placeholder="请输入（最多200个字）"
								autoSize={{minRows: 3, maxRows: 6}}
							/>
						</Form.Item>
					</Col>
				</Row>
			</Form>

			<div className={styles.wrap}>
				<Button
					type="primary"
					htmlType="submit"
					onClick={() => {
						onSave()
					}}>
					保存
				</Button>
				<Button
					onClick={() => {
						history.go(-1)
					}}>
					取消
				</Button>
			</div>
			<Modal
				text="确定要保存吗？请仔细核对所填信息"
				onSubmit={onSubmit}
				loading={btnLoading}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(add)
